package com.jsg.sl651.handler;

import com.jsg.sl651.boot.BootProperties;
import com.jsg.sl651.entity.data.Element;
import com.jsg.sl651.entity.frame.FrameMessageWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.apache.commons.codec.binary.Hex;
import org.jetlinks.core.message.DeviceOnlineMessage;
import org.jetlinks.core.message.property.ReportPropertyMessage;
import org.jetlinks.protocol.official.binary.BinaryDeviceOnlineMessage;
import org.jetlinks.protocol.official.binary.BinaryMessageType;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SL651ToJetLinksByTCP {
    private Socket socket;
    private static InputStream inputStream;
    private static OutputStream outputStream;

    public SL651ToJetLinksByTCP() {
        this.socket = null;
    }

    public void toJetLinks(FrameMessageWrapper frameMessageWrapper) throws Exception {
        System.out.println("in");
        DeviceOnlineMessage message = new DeviceOnlineMessage();
        if(socket == null )deviceOnline(frameMessageWrapper, message);
        if(!frameMessageWrapper.getBody().getDataElements().isEmpty()){
            Map<String, Object> properties = new HashMap<String, Object>();
            for (Element<?> dataElement : frameMessageWrapper.getBody().getDataElements()) {
                System.out.println(dataElement.getHexKey() + "===" + dataElement.getData() + "===" + dataElement.getName());
                if(!dataElement.getName().equals("未知属性") && !dataElement.getName().equals("遥测站状态及报警信息")
                && !dataElement.getName().equals("测站编码引导符")){
                    if(dataElement.getName().equals("观测时间引导符")){
                        String dateTime = dataElement.getData().toString().replace("T"," ");
                        properties.put(dataElement.getHexKey() + "H", dateTime);
                    }else{
                        properties.put(dataElement.getHexKey() + "H", dataElement.getData());
                    }
                }
            }
            ReportPropertyMessage messageContent = new ReportPropertyMessage();
            messageContent.setDeviceId(frameMessageWrapper.getHeader().getRemoteTelemetryStationAddress().getMessageHex());
            messageContent.setProperties(properties);

            ByteBuf dataContent = BinaryMessageType.write(messageContent, Unpooled.buffer());
            ByteBuf bufContent = Unpooled.buffer().writeInt(dataContent.readableBytes()).writeBytes(dataContent);
            System.out.println(ByteBufUtil.hexDump(bufContent));
            outputStream.write(Hex.decodeHex(ByteBufUtil.hexDump(bufContent)));
            outputStream.flush();

            byte[] buffer = new byte[100];// 创建一个字节数组，用于存储接收到的数据
            int length = inputStream.read(buffer);// 读取数据
            String receivedData = Hex.encodeHexString(buffer);// 将字节数组转换为16进制字符串
            System.out.println("Received Content: " + receivedData);
            Thread.sleep(1000*60);// 等待60秒后，没有连接，断开网络链接，并释放相关的内存
        }
    }
    private void deviceOnline(FrameMessageWrapper frameMessageWrapper, DeviceOnlineMessage message) throws Exception{
        message.setDeviceId(frameMessageWrapper.getHeader().getRemoteTelemetryStationAddress().getMessageHex());
        message.addHeader(BinaryDeviceOnlineMessage.loginToken, "admin");
        ByteBuf byteBuf = BinaryMessageType.write(message, Unpooled.buffer());
        ByteBuf buf = Unpooled.buffer().writeInt(byteBuf.readableBytes()).writeBytes(byteBuf);
        System.out.println(ByteBufUtil.hexDump(buf));
        socket = new Socket();
        BootProperties bootProperties = new BootProperties();
        socket.connect(new InetSocketAddress(bootProperties.getIotHost(), bootProperties.getIotPort()), 10000);
        if (socket.isConnected()) {
            System.out.println("已连接");
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            outputStream.write(Hex.decodeHex(ByteBufUtil.hexDump(buf)));
            outputStream.flush();
            byte[] buffer = new byte[30];// 创建一个字节数组，用于存储接收到的数据
            int length = inputStream.read(buffer);// 读取数据
            String receivedData = Hex.encodeHexString(buffer);// 将字节数组转换为16进制字符串
            System.out.println("Received online: " + receivedData);
        }
        Thread.sleep(2000);
    }
}
